package com.zsp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsp.entity.Message;
import com.zsp.entity.Product;
import com.zsp.entity.User;
import com.zsp.entity.param.*;
import com.zsp.entity.vo.AndroidLoginVo;
import com.zsp.entity.vo.LoginVo;
import com.zsp.entity.vo.MessageVo;
import com.zsp.result.Result;
import com.zsp.service.MessageService;
import com.zsp.service.ProductService;
import com.zsp.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.IOUtils;
import redis.clients.jedis.Jedis;

import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;


@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;

    @Autowired
    private ProductService productService;



    @PostMapping("androidLogin")
    public AndroidLoginVo testAndroid(@RequestBody @Valid LoginRequest param){
        if (ObjectUtils.isEmpty(param.getPhone()) || ObjectUtils.isEmpty(param.getPassword())) {
            return new AndroidLoginVo();
        } else {
            AndroidLoginVo loginVo = new AndroidLoginVo();
            loginVo.setCode(200);
            loginVo.setUsername("测试用户名");
            loginVo.setToken("123456");
            loginVo.setType(1);
            loginVo.setUserId(100);
            return loginVo;
        }
    }

    /**
     * 模拟发送了短信验证码
     * @param param
     */
    @PostMapping("getPhoneCode")
    public Integer testAndroid(@RequestBody GetVerificationCodeParam param){
        if (ObjectUtils.isEmpty(param)) {
            return 201;
        } else {
            String verificationCode = generateVerificationCode();
            System.out.println(verificationCode);
            // 发送短信
//            storeVerificationCodeInRedis(param.getPhoneCode(),verificationCode);
            return 200;
        }
    }

    // 生成随机四位验证码
    private static String generateVerificationCode() {
        Random random = new Random();
        int code = 1000 + random.nextInt(9000); // 生成1000到9999之间的随机数
        return String.valueOf(code);
    }
    // 存储验证码到redis，有效期1分钟，RedisKey : haikou_sendMsg_手机号
    private static void storeVerificationCodeInRedis(String phone,String verificationCode) {
        Jedis jedis = new Jedis("localhost"); // 连接本地Redis服务器
        String key = "haikou_sendMsg_" + phone;
        int expireTimeInSeconds = 60; // 设置过期时间为1分钟
        jedis.setex(key, expireTimeInSeconds, verificationCode); // 将验证码存储在Redis并设置过期时间
        System.out.println("验证码已存储在Redis并设置过期时间为1分钟: " + verificationCode);
        jedis.close();
    }
    /**
     * 登录用户
     *
     * @param param
     * @return
     */
    @PostMapping("login")
    public LoginVo login(@RequestBody @Valid LoginParam param) {
        User one = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserphone, param.getPhone())
                .eq(User::getPassword, param.getPassword()));
        if (ObjectUtils.isEmpty(one)) {
            return new LoginVo();
        } else {
            LoginVo loginVo = new LoginVo();
            loginVo.setCode(200);
            loginVo.setUsername(one.getUserphone());
            return loginVo;
        }
    }

    /**
     * 注册用户
     *
     * @param param
     * @return
     */
    @PostMapping("register")
    public LoginVo register(@RequestBody @Valid LoginParam param) {
        User one = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserphone, param.getPhone()));
        if (ObjectUtils.isEmpty(one)) {
            User user = new User();
            user.setUserphone(param.getPhone());
            user.setPassword(param.getPassword());
            boolean save = userService.save(user);
            if (save) {
                LoginVo loginVo = new LoginVo();
                loginVo.setCode(200);
                loginVo.setUsername(param.getPhone());
                return loginVo;
            } else {
                return new LoginVo();
            }

        } else {
            LoginVo loginVo = new LoginVo();
            // 用户已经存在
            loginVo.setCode(201);
            return loginVo;
        }
    }

    /**
     * 留言
     *
     * @param param
     * @return
     */
    @PostMapping("sendRemark")
    public LoginVo sendRemark(@RequestBody MessageParam param) {
        Message message = new Message();
        BeanUtils.copyProperties(param, message);
        message.setCreatetime(LocalDateTime.now());
        if (message.getImage() == null) {
            message.setImage("data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==");
        }
        boolean save = messageService.save(message);
        LoginVo loginVo = new LoginVo();
        if (save) {
            loginVo.setCode(200);
            return loginVo;
        } else {
            loginVo.setCode(201);
            return loginVo;
        }
    }

    /**
     * 后台根据状态获取留言列表
     * 分页查询
     *
     * @return
     */

    @GetMapping("pageList")
    public Result pageList(@RequestBody MessageParam param) {
        return messageService.selectPage(param);
    }

    /**
     * 前台获取留言列表
     *
     * @return
     */
    @GetMapping("getMessage")
    public List<Message> getMessageList(Integer type) {
        List<Message> list = messageService.list(Wrappers.lambdaQuery(Message.class).eq(Message::getType, type));
        return list;
    }

    /**
     * 修改留言信息
     *
     * @param param
     * @return
     */
    @PostMapping("updateMessage")
    public Integer verify(MessageParam param) {
        Message message = new Message();
        BeanUtils.copyProperties(param, message);
        boolean b = messageService.updateById(message);
        if (b) {
            return 200;
        } else {
            return 201;
        }
    }

    /**
     * 审核留言信息
     */
    @PostMapping("verify")
    public Integer verify(@Param("id") Integer id, @Param("type") Integer type) {
        int res = messageService.verify(id, type);
        if (res > 0) {
            return 200;
        } else {
            return 201;
        }
    }

    /**
     * 添加商品
     *
     * @param param
     * @return
     */
    @PostMapping("insertProduct")
    public Integer insertProduct(InsertProductParam param) {
        Product product = new Product();
        BeanUtils.copyProperties(param, product);
        product.setCreateTime(LocalDateTime.now());
        boolean save = productService.save(product);
        if (save) {
            return 200;
        } else {
            return 201;
        }
    }


    /**
     * 前台查询有效商品
     *
     * @return
     */
    @PostMapping("productList")
    public List<Product> productList() {
        List<Product> list = productService.list(Wrappers.lambdaQuery(Product.class).eq(Product::getType, 1));
        return list;
    }

    /**
     * 修改商品信息
     *
     * @param param
     * @return
     */
    @PostMapping("updateProduct")
    public Integer updateProduct(UpdateProductParam param) {
        Product product = new Product();
        BeanUtils.copyProperties(param, product);
        boolean b = productService.updateById(product);
        if (b) {
            return 200;
        } else {
            return 201;
        }
    }

    /**
     * 删除商品
     * @param id
     * @return
     */
    @GetMapping("delProduct")
    public Integer delProduct( @Param("id") Integer id) {
        boolean b = productService.verify(id);
        if (b) {
            return 200;
        } else {
            return 201;
        }
    }

    /**
     * 图片转为base64
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadImage")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 将上传的图片文件转换为Base64格式
            byte[] bytes = IOUtils.toByteArray(file.getInputStream());
            String base64Image = Base64.getEncoder().encodeToString(bytes);
            return "data:image/jpeg;base64," + base64Image; // 注意逗号的添加
        } catch (IOException e) {
            e.printStackTrace();
            return "Error converting image to Base64";
        }
    }
}
